package userservice

import (
	"errors"
	"go-micro-framework/go_service/user/dao"
	"go-micro-framework/go_service/user/model"
	"golang.org/x/crypto/bcrypt"
)

type IUserService interface {
	// AddUser 插入用户
	AddUser(user *model.User) int64
	// DeleteUser 删除用户
	DeleteUser(int64) bool
	// UpdateUser 更新用户
	UpdateUser(user *model.User, isChangePwd bool) bool
	// FindUserByName 根据用户名称查找用户信息
	FindUserByName(string) *model.User
}

// NewUserService 创建实例
func NewUserService() IUserService {
	var userDao = dao.UserDao{}
	return &UserService{userDao: userDao}
}

type UserService struct {
	userDao dao.UserDao
}

func (u *UserService) Dao() *dao.UserDao {
	return &u.userDao
}

// GeneratePassword 加密用户密码
func GeneratePassword(userPassword string) ([]byte, error) {
	return bcrypt.GenerateFromPassword([]byte(userPassword), bcrypt.DefaultCost)
}

// ValidatePassword 验证用户密码
func ValidatePassword(userPassword string, hashed string) (isOk bool, err error) {
	if err = bcrypt.CompareHashAndPassword([]byte(hashed), []byte(userPassword)); err != nil {
		return false, errors.New("密码比对错误")
	}
	return true, nil
}

// AddUser 插入用户
func (u *UserService) AddUser(user *model.User) (userID int64) {
	pwdByte, err := GeneratePassword(user.PassWord)
	if err != nil {
		return user.GetId()
	}
	user.PassWord = string(pwdByte)
	return u.Dao().Save(user)
}

// DeleteUser 删除用户
func (u *UserService) DeleteUser(userID int64) bool {
	return u.Dao().DeleteById(userID)
}

// UpdateUser 更新用户
func (u *UserService) UpdateUser(user *model.User, isChangePwd bool) bool {
	if isChangePwd {
		pwdByte, err := GeneratePassword(user.PassWord)
		if err != nil {
			return false
		}
		user.PassWord = string(pwdByte)
	}
	return u.Dao().Update(user)
}

// FindUserByName 根据用户名称查找用户信息
func (u *UserService) FindUserByName(userName string) *model.User {
	var user = &model.User{UserName: userName}
	return u.Dao().SelectLast(user, dao.USER_SQL_USERNAME)
}

// FindUserByID 根据用户名称查找用户信息
func (u *UserService) FindUserByID(userId int64) *model.User {
	return u.Dao().SelectById(userId)
}
